<template>
  <!-- prefixIcon="search" -->
  <view style="position: relative; overflow: hidden;">
    <uni-easyinput
      style="position: absolute; z-index: 200; width: 80vw; top: 50rpx; left: 50%; transform: translate(-50%,-50%);"
      suffixIcon="search" v-model="searchValue" placeholder="搜索周边" @confirm="searchClick" @iconClick="searchClick"
      confirmType="search">
    </uni-easyinput>
    <!-- 输入提示不知道为何没有用 -->
    <!-- <input id='tipinput' type="text"> -->
    <view id="container" :style="`height: ${contentHeight}px`"></view>
    <Menu ref="MenuRef" :showType="showType" :formData="formData" @changeShowType="changeShowType"
      @getFormData="searchClick"></Menu>
  </view>
</template>

<!-- https://webapi.amap.com/maps?v=2.0&key=3047bf931923a319988f7347cd51ad72&&plugin=AMap.Scale,AMap.HawkEye,AMap.ToolBar,AMap.ControlBar,AMap.AutoComplete,AMap.Driving,AMap.Walking,AMap.Riding,AMap.Transfer -->

<script setup>
  import './maps.js'
  import Menu from "./components/Menu.vue"
  import {
    onUnmounted,
    reactive,
    ref,
  } from "vue";
  import {
    onLoad,
    onReady
  } from "@dcloudio/uni-app";

  let MenuRef = ref(null)
  let contentHeight = ref(null)
  let x = ref(null)
  let y = ref(null)
  let searchValue = ref(null)
  let formData = ref({
    pois: []
  })
  let showType = ref('搜索')
  let map = reactive(null);
  let cityCode = ref(null)

  let auto = new AMap.AutoComplete({
    input: "tipinput"
  });

  const searchClick = (v) => {
    console.log(auto);
    console.log(v, 'searchClick');
    let pageSize = 20
    let pageIndex = 1
    let pois = []
    if (typeof v == 'object') {
      pageSize = v.pageSize
      pageIndex = v.pageIndex
      pois = JSON.parse(JSON.stringify(formData.value.pois))
    }
    // removeMarkers()
    // 搜索位置
    AMap.plugin(["AMap.PlaceSearch"], function() {
      const placeSearch = new AMap.PlaceSearch({
        pageSize: pageSize, //单页显示结果条数
        pageIndex: pageIndex, //页码
        city: cityCode.value, //兴趣点城市
        citylimit: true, //是否强制限制在设置的城市内搜索
        map: map, //展现结果的地图实例
        // panel: "my-panel", //参数值为你页面定义容器的 id 值<div id="my-panel"></div>，结果列表将在此容器中进行展示。
        autoFitView: true, //是否自动调整地图视野使绘制的 Marker 点都处于视口的可见范围
      });
      placeSearch.search(searchValue.value, (status, result) => {
        // 搜索成功时，result即是对应的匹配数据
        console.log(result.poiList);
        showType.value = '搜索'
        if (result.poiList && result.poiList.pois && result.poiList.pois.length) {
          // let marks = result.poiList.pois.map((v) => [v.location.lng, v.location.lat])
          console.log(result.poiList.pois);
          MenuRef.value.openPlan()
          if (pois.length) {
            result.poiList.pois = [...pois, ...result.poiList.pois]
            formData.value = result.poiList
          } else {
            formData.value = result.poiList
          }
        }
      });
    });
  }

  const changeShowType = (v) => {
    showType.value = v.type
    console.log(v, '到这里去!');
    if (v.type == '路线') {
      getTravel(v.name, v.pos)
    }
  }

  const getTravel = (type, pos) => {
    if (!type) return
    //构造路线导航类
    let travel = null
    if (type == 'Driving') {
      // 汽车的路线
      travel = new AMap.Driving({
        map: map,
      });
    } else if (type == 'Walking') {
      // 走路的路线
      travel = new AMap.Walking({
        map: map,
      });
    } else if (type == 'Transfer') {
      // 公交的路线
      travel = new AMap.Transfer({
        map: map,
      });
    } else if (type == 'Riding') {
      // 骑车的路线
      travel = new AMap.Riding({
        map: map,
      });
    }

    travel.clear()

    // 根据起终点经纬度规划导航路线
    travel.search(new AMap.LngLat(x.value, y.value), new AMap.LngLat(...pos), function(status,
      result) {
      if (status === 'complete') {
        console.log('绘制路线完成', result)
        map.setCenter([result.destination.lng, result.destination.lat])
      } else {
        console.log('获取数据失败：' + result)
      }
    });
  }

  onLoad(() => {
    if (!uni.getLocation) {
      return uni.showModal({
        title: '提示',
        content: '请开启定位服务',
        success: function(res) {
          if (res.confirm) {
            // 引导用户到设置页开启定位服务
          }
        }
      });
    }
    uni.showLoading({
      title: '系统正在定位'
    });
  });

  onReady(() => {
    uni.getSystemInfo({
      success: function(info) {
        console.log(info);
        // 获取屏幕的高度
        let windowHeight = info.windowHeight;
        // // 获取状态栏的高度
        // let statusBarHeight = info.statusBarHeight;
        // // windowTop
        // let navigationBarHeight = info.windowTop;
        // // windowBottom
        // let tabBarHeight = info.windowBottom;

        // 计算除去头部和底部之后的内容高度
        contentHeight.value = windowHeight
        initMapBox()
      }
    })
  })

  onUnmounted(() => {
    map?.destroy();
  });

  const initMapBox = () => {
    uni.getLocation({
      altitude: true, // 精确定位
      buttonPosition: 'RB', //定位按钮的停靠位置
      success: (res) => {
        uni.showToast({
          title: '定位成功',
        });

        // 经纬度：120.312000,31.493099
        console.log(res)
        x.value = res.longitude
        y.value = res.latitude
        let options = {
          longitude: res.longitude,
          latitude: res.latitude,
        }

        initMap(options);
        getLocation(res)
      },
      fail: () => {
        uni.hideLoading();
        uni.showToast({
          icon: 'error',
          title: '定位失败',
        });
      }
    })
  }

  const initMap = (options) => {
    let scale = new AMap.Scale({
      position: {
        top: '60px',
        right: '20px'
      }
    })
    let toolBar = new AMap.ToolBar({
      position: {
        top: '100px',
        right: '20px'
      }
    })
    map = new AMap.Map('container', {
      // 设置地图容器id
      pitch: 20, // 角度，有效范围 0 度- 83 度
      terrain: true,
      viewMode: "3D", // 是否为3D地图模式
      zoom: 15, // 初始化地图级别
      center: [options.longitude, options.latitude] // 初始化地图中心点
    });
    // 设置标记点位
    const marker = new AMap.Marker({
      position: [options.longitude, options.latitude], // 设置点位经纬度
      icon: new AMap.Icon({ // 添加 Icon 图标 URL
        image: '/static/star.png',
        size: new AMap.Size(22, 28), //图标所处区域大小
        imageSize: new AMap.Size(22, 28) //图标大小
      }),
    })

    map.add(marker) // 添加到地图
    map.addControl(scale); // 比例尺
    map.addControl(toolBar); // 缩放
  }

  const getLocation = (res) => {
    const latitude = res.latitude;
    const longitude = res.longitude;
    const amapKey = '3047bf931923a319988f7347cd51ad72';
    const url = `https://restapi.amap.com/v3/geocode/regeo?key=${amapKey}&location=${longitude},${latitude}`;
    uni.request({
      url: url,
      success: (response) => {
        console.log('response.data', response.data);
        if (response.data && response.data.infocode) {
          cityCode.value = response.data.infocode
        }
      },
      fail: (error) => {
        console.error('获取城市失败：', error);
      }
    })
  }

  // 清除所有点标记
  const removeMarkers = () => {
    map.remove(markers);
  }
</script>
<style lang="scss" scoped>
  #container {
    width: 100%;
  }
</style>
